<template>
  <div class="action-management">
    <a-card>
      <div class="buttons">
        <a-button
          icon="plus"
          type="primary"
          class="mb-[10px]"
          @click="openModal()"
          >{{ $t("system.actionmanage.add") }}</a-button
        >
      </div>
      <a-table
        :columns="columns"
        :dataSource="dataSource"
        :pagination="{ total }"
        @change="getActionList"
      >
        <template slot="ActionUpdatetime" slot-scope="text, record">
          {{ record.ActionUpdatetime || record.ActionCreatetime }}
        </template>
        <template slot="operate" slot-scope="text, record">
          <a-button type="link" @click="openModal(record.Id)">{{
            $t("user.verification-code.required111566147")
          }}</a-button>
          <a-popconfirm
            :title="$t('user.verification-code.required111566110577225')"
            :ok-text="$t('user.verification-code.required1166')"
            :cancel-text="$t('user.email.required11')"
            @confirm="() => delRow(record.Id)"
          >
            <a-button type="link">{{ $t("app.setting.copy") }}</a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-card>
    <a-modal
      :title="$t('user.verification-code.required111566164')"
      :visible="visible"
      :width="680"
      :ok-text="$t('user.verification-code.required1166')"
      :cancel-text="$t('user.email.required11')"
      dialogClass="action-manage-modal"
      @ok="createAction"
      @cancel="onChildrenDrawerClose"
    >
      <a-form
        :form="form"
        labelAlign="left"
        :label-col="{ span: lang ? 8 : 11 }"
        :wrapper-col="{ span: lang ? 16 : 13 }"
      >
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item :label="$t('system.actionmanage.modal.form.type')">
              <a-select v-decorator="['ActionType', { initialValue: 1 }]">
                <a-select-option v-for="item in typeList" :key="item.value">
                  {{ $t(item.label) }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item :label="$t('system.actionmanage.modal.form.id')">
              <a-input v-decorator="['ActionId']" disabled />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item
              :label="$t('user.verification-code.required111566172')"
            >
              <a-input
                v-decorator="['ActionName']"
                :placeholder="$t('user.verification-code.required111566172')"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item
              style="margin: 0"
              :label="$t('user.verification-code.required111566173')"
            >
              <a-textarea
                :auto-size="{ minRows: 3, maxRows: 10 }"
                :placeholder="$t('user.verification-code.required11156617311')"
                :rows="3"
                v-decorator="['ActionInfo']"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="12">
            <a-form-item
              :label="$t('user.verification-code.required111566110571111')"
            >
              <a-input-number
                v-decorator="['ActionWeight']"
                :placeholder="
                  $t('user.verification-code.required111566110571111')
                "
                style="width: 100%"
                :min="0"
                :precision="0"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <label class="self-label">
          {{ $t("user.verification-code.required111566178") }}:
        </label>
        <a-timeline>
          <a-timeline-item v-for="item in inputList" :key="item.Id">
            <a-space size="0" align="center">
              <p style="min-width: 150px">
                {{ item.actionCreateUser || actionCreateUser }}
                {{ item.actionCreateTime }}
              </p>
              <a-button type="link" @click="saveRemarkList([item])"
                >{{ $t("user.verification-code.required1166") }}
              </a-button>
              <a-button type="link" @click="deleteInput(item.Id)">{{
                $t("app.setting.copy")
              }}</a-button>
            </a-space>
            <a-form-item>
              <a-textarea
                :auto-size="{ minRows: 3, maxRows: 10 }"
                :placeholder="$t('user.verification-code.required111566182')"
                :rows="3"
                v-model="item.ActionRemarkInfo"
              />
            </a-form-item>
          </a-timeline-item>
          <div class="buttons">
            <a-button @click="addInput"
              >{{ $t("user.verification-code.required1115661106888") }}
            </a-button>
          </div>
        </a-timeline>
        <a-row :gutter="24">
          <a-col :span="14">
            <a-form-item :label="$t('system.actionmanage.modal.form.load')">
              <a-radio-group
                v-decorator="[
                  'ActionLoad',
                  {
                    initialValue: 1,
                    rules: [
                      {
                        required: true,
                        message: $t('breach.steps.step1.content.form.tip1'),
                      },
                    ],
                  },
                ]"
              >
                <a-radio :value="1">{{ $t("user.v163") }}</a-radio>
                <a-radio :value="2">{{ $t("user.v164") }}</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="18">
            <a-form-item
              :label="$t('system.actionmanage.modal.form.template')"
              v-if="
                form.getFieldValue('ActionLoad') === undefined
                  ? true
                  : form.getFieldValue('ActionLoad')
              "
              :required="true"
            >
              <a-select v-decorator="['ActionModels']">
                <a-select-option v-for="item in sourceList" :key="item.value">
                  {{ $t(item.label) }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import moment from "moment";
import { typeList } from "@/staticLists/breach";
import {
  createActionMode,
  deleteRemark,
  getActionListPost,
  getActionModalDetail,
  getActionRemarkList,
  updateActionMode,
} from "@/api/dataBreach/form";
import { createRemark, updateRemark } from "@/api/dataBreach/json";
export default {
  name: "actionManagement",
  data() {
    return {
      visible: false,
      columns: [
        {
          title: () => this.$t("system.actionmanage.table.id"),
          dataIndex: "ActionId",
          key: "ActionId",
        },
        {
          title: () => this.$t("system.actionmanage.table.name"),
          dataIndex: "ActionName",
          key: "ActionName",
        },
        {
          title: () => this.$t("system.actionmanage.table.type"),
          key: "ActionType",
          dataIndex: "ActionType",
        },
        {
          title: () => this.$t("breach.list.content.table.creatorcopy"),
          dataIndex: "ActionCreateUser",
          key: "ActionCreateUser",
        },
        {
          title: () => this.$t("breach.list.content.table.createtime"),
          dataIndex: "ActionCreatetime",
          key: "ActionCreatetime",
        },
        {
          title: () => this.$t("system.actionmanage.table.updatetime"),
          dataIndex: "ActionUpdatetime",
          key: "ActionUpdatetime",
          scopedSlots: { customRender: "ActionUpdatetime" },
        },
        {
          title: () => this.$t("di.menus"),
          key: "operate",
          scopedSlots: { customRender: "operate" },
        },
      ],
      dataSource: [],
      typeList,
      form: this.$form.createForm(this),
      lang: localStorage.getItem("lang").includes("zh-CN"),
      inputList: [],
      actionCreateUser: "",
      sourceList: [
        { label: "breach.list.content.table.source.breach", value: 1 },
        { label: "breach.list.content.table.source.dlp", value: 2 },
      ],
      currentData: {},
      total: 0,
    };
  },
  mounted() {
    this.actionCreateUser = this.$store.state.user.info.name;
    this.getActionList();
    this.addInput();
    window.addEventListener("beforeunload", this.onChildrenDrawerClose);
    let that = this;
    window.addEventListener("setItemEvent", function (e) {
      if (e.key == "lang") {
        that.lang = e.value.includes("zh-CN");
      }
    });
  },
  beforeDestroy() {
    window.removeEventListener("beforeunload", this.onChildrenDrawerClose);
  },
  methods: {
    async delRow(Id) {
      let { code } = await deleteRemark({ Id });
      if (code === 1) {
        this.$message.success(
          this.$t("user.verification-code.required111566110577133")
        );
        this.getActionList();
      }
    },
    async getActionList(pagination) {
      let { data } = await getActionListPost({
        page: pagination?.current || 1,
        pageSize: pagination?.pageSize || 10,
      });
      this.dataSource = data.Lists;
      this.total = data.Total;
    },
    // 新建编辑action
    createAction() {
      this.form.validateFields(async (err, value) => {
        if (!err) {
          let { code } = await updateActionMode({
            Id: this.currentData.Id,
            ...value,
          });
          this.saveRemarkList();
          if (code === 1) {
            this.onChildrenDrawerClose(false);
          }
        }
      });
    },
    async onChildrenDrawerClose(ifDel = true) {
      this.form.resetFields();
      this.inputList = [];
      if (ifDel && !this.currentData.Id) {
        await deleteRemark({ Id: this.currentData.Id });
      }
      this.getActionList();
      this.visible = false;
    },
    // 添加
    addInput() {
      // 新增一个新的数据初始化
      this.inputList.push({
        Id: +new Date(),
        ActionRemarkInfo: "",
        actionCreateTime: moment().format("YYYY-MM-DD HH:mm:ss"),
        actionCreateUser: this.actionCreateUser,
      });
    },
    async deleteInput(Id) {
      if (Id > 1000000) {
        this.inputList = this.inputList.filter((item) => item.Id !== Id);
      } else {
        let { code } = await deleteRemark({ Id });
        if (code === 1) {
          this.inputList = this.inputList.filter((item) => item.Id !== Id);
        }
      }
    },
    async openModal(Id) {
      let { data } = Id
        ? await getActionModalDetail({ Id })
        : await createActionMode();
      this.currentData = data;
      setTimeout(() => {
        let dataCopy = { ...data };
        dataCopy.ActionWeight = dataCopy.ActionWeight
          ? dataCopy.ActionWeight
          : undefined;
        dataCopy.ActionModels = dataCopy.ActionModels
          ? dataCopy.ActionModels
          : 1;
        setTimeout(() => {
          this.form.setFieldsValue(dataCopy);
        }, 400);
      });
      if (Id) {
        // 编辑-获取备注列表
        let { data } = await getActionRemarkList({
          ActionId: Id,
          ActionType: 1,
        });
        this.inputList = data;
        if (!this.inputList.length) {
          this.addInput();
        }
      }
      this.visible = true;
    },
    saveRemarkList(list = this.inputList) {
      let newRemark = []; // 新建的备注
      let changeRemark = []; // 修改的备注
      let deleteRemark = []; // 删除的备注
      list.forEach((item) => {
        if (item.ActionRemarkInfo) {
          if (!item.Id || item.Id > 1000000) {
            item.Id = undefined;
            item.ActionType = 1;
            item.actionCreateTime = undefined;
            item.actionCreateUser = undefined;
            item.ActionId = this.currentData.Id;
            newRemark.push(item);
          } else {
            changeRemark.push(item);
          }
        } else if (item.Id < 1000000) {
          deleteRemark.push(item);
        }
      });
      if (newRemark.length) {
        createRemark(newRemark);
      }
      if (changeRemark.length) {
        updateRemark(changeRemark);
      }
      if (deleteRemark.length) {
        deleteRemark.forEach((item) => {
          deleteRemark({
            Id: item.Id,
          });
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.action-management {
  .buttons {
    display: flex;
    flex-direction: row-reverse;
  }
}
</style>
<style lang="less">
.action-manage-modal {
  .ant-form-item {
    margin-bottom: 12px;
    textarea {
      resize: none;
    }
  }
  .self-label {
    color: rgba(0, 0, 0, 0.85);
    line-height: 40px;
  }
  .ant-timeline {
    .ant-form-item-control-wrapper {
      width: 100%;
    }
    .buttons {
      display: flex;
      flex-direction: row-reverse;
    }
  }
}
</style>